import random
import re
from datetime import datetime

from flask import abort, jsonify
from flask import current_app
from flask import make_response
from flask import request
from flask import session

from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info import redis_store, db
from info import constants
from info.utils.captcha.response_code import RET

from . import passport_blu


@passport_blu.route("/image_code")
def image():
    image_code_id = request.args.get("imageCodeId")
    if not image_code_id:
        abort(403)

    name, text, image = captcha.generate_captcha()
    try:
        redis_store.set("imageCodeId_" + image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        abort(500)
        current_app.logger.error(e)

    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    return response


@passport_blu.route("/sms_code", methods=["POST"])
def sms():
    data = request.json
    print(data)
    mobile = data.get("mobile")
    image_code = data.get("image_code")
    image_code_id = data.get("image_code_id")

    if not all([mobile, image_code_id, image_code]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not re.match(r"1[35678]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")

    user = User.query.filter(User.mobile == mobile).first()
    if user:
        return jsonify(errno=RET.REQERR, errmsg="手机号已注册！")

    try:
        real_image_code = redis_store.get("imageCodeId_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码已过期")

    if real_image_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")

    sms_code_str = "%06d" % random.randint(0, 999999)
    # result = CCP().send_template_sms(mobile, [sms_code_str, constants.SMS_CODE_REDIS_EXPIRES/60], "1")
    #
    # if result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="短信发送失败")
    print(sms_code_str)
    try:
        redis_store.set("SMS_" + mobile, sms_code_str, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route("/register", methods=["POST"])
def register():
    data = request.json
    print(data)
    mobile = data.get("mobile")
    smscode = data.get("smscode")
    password = data.get("password")

    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        real_sms_code = redis_store.get("SMS_" + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码已过期")

    if smscode != real_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password
    user.last_login = datetime.now()

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    session["user_id"] = user.id
    session["user_name"] = user.nick_name
    session["user_mobile"] = user.mobile

    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route("/login", methods=["POST"])
def login():
    data = request.json
    print(data)
    mobile = data.get("mobile")
    password = data.get("password")

    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not re.match(r"1[35678]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not user:
        return jsonify(errno=RET.DATAERR, errmsg="该手机号未注册")

    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg="用户名或密码错误")

    session["user_id"] = user.id
    session["user_name"] = user.nick_name
    session["user_mobile"] = user.mobile
    user.last_login = datetime.now()

    return jsonify(errno=RET.OK, errmsg="登录成功")


@passport_blu.route("/logout")
def logout():

    session.pop("user_id", None)
    session.pop("user_name", None)
    session.pop("user_mobile", None)

    return jsonify(errno=RET.OK, errmsg="退出成功")